package com.etl.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.rest.RestStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.util.Objects;

@Slf4j
@Configuration
public class ElasticSearchClient {

    @Autowired
    RestHighLevelClient highLevelClient;

    /**
     * 封装ElasticSearchClient查询方法
     *
     * @param searchRequest 查询请求参数
     * @return SearchResponse 查询结果
     */
    public SearchResponse search(SearchRequest searchRequest) {
        try {
            log.debug("elasticSearchClient.search.request: {}", searchRequest);
            SearchResponse response = highLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            log.debug("elasticSearchClient.search.response: {}", response);
            if (Objects.isNull(response)) {
                throw new ElasticsearchException("The SearchResponse is null");
            }
            if (!RestStatus.OK.equals(response.status())) {
                throw new ElasticsearchException("The SearchResponse status is not 200");
            }
            return response;
        } catch (Exception e) {
            return ExceptionUtils.rethrow(e);
        }
    }
}
